package webapi

import (
	"net/http"

	"webSer/memdb"
	"webSer/mqttser"

	us "gitee.com/gouyabin/go_utils"
	jrpc "gitee.com/gouyabin/jsonrpc"
)

type MqttClient struct{}

type Mqtt struct{}

type MqttPubArgs struct {
	Topic   string      `json:"topic"`
	PubJson interface{} `json:"pubjson"`
}

type ResultData struct {
	Data interface{} `json:"data"`
}
type MqttArgs struct {
	Name string `json:"name"`
}

func (q *Mqtt) Pub(args *MqttPubArgs, reply *ResultData) error {
	mqttser.Publish(args.Topic, args.PubJson)
	reply.Data = "ok"
	return nil
}

func (q *Mqtt) SubList(args *MqttArgs, reply *ResultData) error {

	reply.Data = memdb.MqttDBList.GetAll()
	return nil
}

func (m *MqttClient) GetClientAll(args *MqttArgs, reply *ResultData) error {
	reply.Data = memdb.MqttClient.GetAll()
	return nil
}

var Log *us.Logs

func WebApiInit() {
	Log = us.Log
	srv := jrpc.NewServerWithCodec(jrpc.NewJSONCodec())
	srv.AuthCheck = new(jrpc.Auth)
	srv.AuthCheck.AuthState = true
	srv.AuthCheck.NoAuthMethod = []string{"User.Login"}
	srv.AuthCheck.AuthCheckFunc = AuthCheck
	srv.Register(&User{})
	srv.Register(new(Mqtt))
	srv.Register(new(MqttClient))
	http.Handle("/api", srv)
	http.ListenAndServe(":8001", nil)
}

//验证权限
func AuthCheck(a string) bool {
	ErrInt, _ := memdb.CheckAuth(a)
	if ErrInt != 0 {
		Log.Info("登录失败", ErrInt)
		return false
	}
	return true
}
